/**
 * 
 */
package com.googlecode.xcarve.netty.server;

import io.netty.util.internal.chmv8.ConcurrentHashMapV8;

import java.util.Map;

import com.googlecode.xcarve.object.RPCRequest;

/**
 * @author xinyun.d
 * 2014年10月1日
 */
public class ServiceExport{
	public static final Map<String,ServiceProxy> serviceMap = new ConcurrentHashMapV8<String,ServiceProxy>(); 
	
	private static final ServiceExport instance = new ServiceExport();
	
	private ServiceExport(){
	}
	
	public static ServiceExport getInstance(){
		return instance;
	}
	
	public static <T> void export(Class<?> service, T serviceImpl){
		ServiceProxy proxy = serviceMap.get(service.getName());
		if(proxy == null){
			DynamicProxy<T> dynamicProxy = new DynamicProxy<T>();
			proxy = dynamicProxy.getServiceProxy(service, serviceImpl);
			serviceMap.put(service.getName(), proxy);
		}
	}
	
	public <T> void exportService(Class<?> service, T serviceImpl){
		ServiceProxy proxy = serviceMap.get(service.getName());
		if(proxy == null){
			DynamicProxy<T> dynamicProxy = new DynamicProxy<T>();
			proxy = dynamicProxy.getServiceProxy(service, serviceImpl);
			serviceMap.put(service.getName(), proxy);
		}
	}
	
	public ServiceProxy getServiceProxy(RPCRequest request){
		return serviceMap.get(request.getService().getName());
	}
	
	public Object invoke(RPCRequest request) throws Throwable{
		return serviceMap.get(request.getService().getName()).invoke(request);
	}
	
}
